<template>
  <div class="flex flex-col gap-4">
    <div class="flex items-center justify-between">
      <h1 class="text-3xl font-bold tracking-tight">单词管理</h1>
      <RouterLink to="/words/new">
        <Button>
          <PlusCircleIcon class="mr-2 h-4 w-4" />
          添加单词
        </Button>
      </RouterLink>
    </div>

    <Card>
      <CardHeader>
        <CardTitle>词汇管理</CardTitle>
        <CardDescription>添加、编辑和删除词汇数据库中的单词。</CardDescription>
      </CardHeader>
      <CardContent>
        <div class="flex justify-between items-center pb-4">
          <Input
              placeholder="搜索单词..."
              class="max-w-sm"
              v-model="searchQuery"
              @input="handleSearchInput"
          />
        </div>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>ID</TableHead>
              <TableHead>单词</TableHead>
              <TableHead>发音</TableHead>
              <TableHead>词性</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            <TableRow v-for="word in words" :key="word.id">
              <TableCell>{{ word.id }}</TableCell>
              <TableCell>{{ word.word }}</TableCell>
              <TableCell>{{ word.pronunciation }}</TableCell>
              <TableCell>{{ word.partOfSpeech }}</TableCell>
              <TableCell>
                <DropdownMenu>
                  <DropdownMenuTrigger as-child>
                    <Button variant="ghost" class="h-8 w-8 p-0">
                      <span class="sr-only">打开菜单</span>
                      <MoreHorizontalIcon class="h-4 w-4"/>
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuItem as-child>
                      <RouterLink :to="'/words/' + word.id">
                        <EyeIcon class="mr-2 h-4 w-4"/>
                        查看
                      </RouterLink>
                    </DropdownMenuItem>
                    <DropdownMenuItem as-child>
                      <RouterLink :to="'/words/' + word.id + '/edit'">
                        <PencilIcon class="mr-2 h-4 w-4"/>
                        编辑
                      </RouterLink>
                    </DropdownMenuItem>
                    <DropdownMenuItem
                        class="text-destructive focus:text-destructive"
                        @click="handleDeleteWord(word)"
                    >
                      <TrashIcon class="mr-2 h-4 w-4"/>
                      删除
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </TableCell>
            </TableRow>
          </TableBody>
        </Table>

        <!-- 分页控件 -->
        <div class="flex items-center justify-between px-2 py-4">
          <div class="flex-1 text-sm text-muted-foreground">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页，显示 {{ (currentPage - 1) * pageSize + 1 }}-{{ Math.min(currentPage * pageSize, totalItems) }} 条，共 {{ totalItems }} 条
          </div>
          <div class="flex items-center space-x-2">
            <Button
                variant="outline"
                size="sm"
                :disabled="currentPage === 1"
                @click="goToPage(currentPage - 1)"
            >
              上一页
            </Button>

            <!-- 页码输入框 -->
            <div class="flex items-center space-x-1">
              <span class="text-sm text-muted-foreground">前往</span>
              <Input
                  type="number"
                  :min="1"
                  :max="totalPages"
                  class="w-16 h-8 text-center"
                  v-model="pageInput"
                  @keyup.enter="goToInputPage"
              />
              <span class="text-sm text-muted-foreground">页</span>
            </div>

            <div class="flex items-center space-x-1">
              <Button
                  v-for="page in visiblePages"
                  :key="page"
                  variant="outline"
                  size="sm"
                  :class="currentPage === page ? 'bg-primary text-primary-foreground' : ''"
                  @click="goToPage(page)"
              >
                {{ page }}
              </Button>
              <span v-if="showEllipsis" class="px-2">...</span>
            </div>
            <Button
                variant="outline"
                size="sm"
                :disabled="currentPage === totalPages || totalPages === 0"
                @click="goToPage(currentPage + 1)"
            >
              下一页
            </Button>
            <Select v-model="pageSize" @update:modelValue="handlePageSizeChange">
              <SelectTrigger class="w-24">
                <SelectValue placeholder="选择数量" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem :value="10">10 条/页</SelectItem>
                <SelectItem :value="20">20 条/页</SelectItem>
                <SelectItem :value="50">50 条/页</SelectItem>
                <SelectItem :value="100">100 条/页</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </CardContent>
    </Card>

    <!-- 删除确认对话框 -->
    <AlertDialog :open="showDeleteDialog" @update:open="showDeleteDialog = $event">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>确定要删除吗？</AlertDialogTitle>
          <AlertDialogDescription>
            此操作无法撤消。这将永久删除此单词及其所有相关数据。
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>取消</AlertDialogCancel>
          <AlertDialogAction
              @click="confirmDelete"
              class="bg-destructive text-destructive-foreground hover:bg-destructive/90"
          >
            删除
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  </div>
</template>

<script setup>
import { onMounted, ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from '@/components/ui/toast'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { PlusCircle as PlusCircleIcon ,MoreHorizontalIcon,EyeIcon,PencilIcon,TrashIcon} from 'lucide-vue-next'
// 单词操作组件
import wordAPI from '@/api/word.js'

const router = useRouter()
const { toast } = useToast()
const searchQuery = ref('')
const showDeleteDialog = ref(false)
const wordToDelete = ref(null)
const pageInput = ref('')

// 分页相关状态
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)
const allWords = ref([]) // 存储所有单词数据

const words = ref([])
const loading = ref(false)

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(totalItems.value / pageSize.value) || 1
})

// 计算可见的页码按钮
const visiblePages = computed(() => {
  const pages = []
  const maxVisiblePages = 5

  if (totalPages.value <= 1) return []

  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2))
  let endPage = Math.min(totalPages.value, startPage + maxVisiblePages - 1)

  if (endPage - startPage + 1 < maxVisiblePages) {
    startPage = Math.max(1, endPage - maxVisiblePages + 1)
  }

  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }

  return pages
})

// 是否显示省略号
const showEllipsis = computed(() => {
  return totalPages.value > visiblePages.value.length &&
      visiblePages.value[visiblePages.value.length - 1] < totalPages.value
})

// 获取所有单词
const fetchWords = async () => {
  try {
    loading.value = true
    const response = await wordAPI.getWords()
    if (response.code === 200) {
      allWords.value = response.data
      totalItems.value = response.data.length
      updateDisplayedWords()
    }
  } catch (error) {
    console.error('获取单词列表失败:', error)
    toast({
      title: "获取失败",
      description: error.response?.data?.message || "无法获取单词列表",
      variant: "destructive"
    })
  } finally {
    loading.value = false
  }
}

// 更新显示的单词列表
const updateDisplayedWords = () => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  // 如果有搜索查询，先过滤数据
  let filteredWords = allWords.value
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filteredWords = allWords.value.filter(w =>
        w.word.toLowerCase().includes(query) ||
        (w.pronunciation && w.pronunciation.toLowerCase().includes(query)) ||
        (w.partOfSpeech && w.partOfSpeech.toLowerCase().includes(query))
    )
  }

  totalItems.value = filteredWords.length
  words.value = filteredWords.slice(startIndex, startIndex + pageSize.value)

  // 如果当前页没有数据且不是第一页，回到上一页
  if (words.value.length === 0 && currentPage.value > 1) {
    currentPage.value = Math.max(1, Math.ceil(totalItems.value / pageSize.value))
    updateDisplayedWords()
  }
}

// 跳转到指定页
const goToPage = (page) => {
  if (page < 1 || page > totalPages.value) return
  currentPage.value = page
  updateDisplayedWords()
  pageInput.value = ''
}

// 处理输入框跳转
const goToInputPage = () => {
  if (!pageInput.value) return

  const pageNum = parseInt(pageInput.value)
  if (isNaN(pageNum) || pageNum < 1 || pageNum > totalPages.value) {
    toast({
      title: "输入错误",
      description: `请输入有效的页码 (1-${totalPages.value})`,
      variant: "destructive"
    })
    pageInput.value = ''
    return
  }

  goToPage(pageNum)
}

// 处理每页显示数量变化
const handlePageSizeChange = (newSize) => {
  pageSize.value = parseInt(newSize)
  currentPage.value = 1 // 重置到第一页
  updateDisplayedWords()
}

// 处理搜索输入
const handleSearchInput = () => {
  // 使用防抖优化搜索性能
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    currentPage.value = 1 // 搜索时重置到第一页
    updateDisplayedWords()
  }, 300)
}

let searchTimeout

const handleDeleteWord = (word) => {
  wordToDelete.value = word
  showDeleteDialog.value = true
}

const confirmDelete = async () => {
  try {
    const response = await wordAPI.deleteWord(wordToDelete.value.id)
    if (response.code === 200) {
      // 从列表中移除
      const index = allWords.value.findIndex(w => w.id === wordToDelete.value.id)
      if (index !== -1) {
        allWords.value.splice(index, 1)
        totalItems.value = allWords.value.length
        updateDisplayedWords()
      }

      toast({
        title: "单词已删除",
        description: `单词 "${wordToDelete.value.word}" 已成功删除。`,
      })
    }
  } catch (error) {
    console.error('删除单词失败:', error)
    toast({
      title: "删除失败",
      description: error.response?.data?.message || "无法删除单词",
      variant: "destructive"
    })
  } finally {
    showDeleteDialog.value = false
    wordToDelete.value = null
  }
}

// 监听搜索查询变化
watch(searchQuery, () => {
  currentPage.value = 1 // 搜索时重置到第一页
  updateDisplayedWords()
})

onMounted(() => {
  fetchWords()
})
</script>
